#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "user.h"

int login(User* user){
	for(int i=0;i<LIMIT_FAIL_LOGIN;i++){
		printf("输入用户名:");
		scanf("%s", user->username);
		printf("输入密码:");
		scanf("%s", user->passwd);
		if(existsInUserFile(user->username, user->passwd))
			return 1;//登录成功
		printf("用户名或密码错误，你还有[%d]次机会\n", LIMIT_FAIL_LOGIN-i-1);
	}	
	return 1;	
}

int existsInUserFile(char *username, char *passwd){
	FILE *fp=fopen(PATH_OF_USER,"r");
	if(fp == NULL){
		perror("文件打开失败");
		return -1;
	}
	User u2;
	int matched=0;
	while(fscanf(fp, "%s %s", u2.username, u2.passwd) != EOF){
		if(strcmp(u2.username,username)!=0)
			continue;
		if(strcmp(u2.passwd,passwd)!=0)
			continue;
		matched=1;
		break;
	}

	fclose(fp);
	return matched;
}
